<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>主页</title>
    <script src="jquery.min.js"></script>

    <script type="text/javascript">

        var ws;
        var token;
        var url = "ws://localhost:8082/communication/websocket"

        function connect() {
            //通过app后台获取token
            $.post("token?userName=" + $("#user-name").val(), function (result) {
                var r = JSON.parse(result);
                token = r.data;
                ws = new WebSocket(url + "?token=" + token);
                initWs()
            });
        }

        function send() {
            //发送消息至websocket服务器
            var object = new Object();
            object.to = $("#receiver").val();
            object.text = $("#message").val();
            object.code = 105;
            ws.send(JSON.stringify(object));
            $("#receiveMsg").val($("#receiveMsg").val() + "发送消息------>" + $("#receiver").val() + "--->:" + $("#message").val() + "\r\n");
        }

        var heartCheck = {
            timeout: 60000,//60s
            timeoutObj: null,
            serverTimeoutObj: null,
            reset: function () {
                //收到websocket消息,重置心跳检测定时器
                clearTimeout(this.timeoutObj);
                clearTimeout(this.serverTimeoutObj);
                this.start();
            },
            start: function () {
                //心跳检测,60s内没有收到服务器消息,会向服务器发送一条心跳消息,发送之后60s收不到服务器消息则重连
                var self = this;
                this.timeoutObj = setTimeout(function () {
                    var object = new Object();
                    object.code = 200;
                    ws.send(JSON.stringify(object));
                    self.serverTimeoutObj = setTimeout(function () {
                        ws.close();//如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
                    }, self.timeout)
                }, this.timeout)
            },
        }
        var reconnet = false;
        function initWs() {
            ws.onopen = function () {
                //心跳检测
                reconnet = true;
                heartCheck.start();
            };
            ws.onmessage = function (event) {
                //收到服务端消息,重置心跳定时器
                heartCheck.reset();
                var data = JSON.parse(event.data);
                if (data.code == 400) {
                    //重复登录被提出,停止心跳检测
                    alert("重复登录被提出");
                    ws.onclose = null;
                    ws.onerror = null;
                    clearTimeout(heartCheck.timeoutObj);
                    clearTimeout(heartCheck.serverTimeoutObj);
                }
                $("#receiveMsg").val($("#receiveMsg").val() + "接收消息------>" + event.data + "\r\n");
            }
            ws.onclose = function () {
                //close时重新连接
                if(reconnet) {
                    reconnect();
                }
            };
            ws.onerror = function () {
                //错误时重新连接
                if(reconnet) {
                    reconnect();
                }
            };
        }

        function reconnect() {
            //重现连接代码
            ws.onopen = null;
            ws.onmessage = null;
            ws.onclose = null;
            ws.onerror = null;
            clearTimeout(heartCheck.timeoutObj);
            clearTimeout(heartCheck.serverTimeoutObj);
            reconnet = false;
            ws = new WebSocket(url + "?token=" + token);
            initWs();
        }

    </script>
</head>
<body>
<h1>Welcome !!!</h1>
用户名:<input type="text" id="user-name"/> <input type="button" value="连接" onclick="connect()"/>
<br/>
发送消息:<br/>
接受者:<input type="text" id="receiver"/><br/>
消息:<input type="text" id="message"/><br/>
<input type="button" value="发送" onclick="send()"/>
<br/>
<br/>
接受消息:<br/>
<textarea id="receiveMsg" style="height: 250px;width: 800px;" readonly="true"></textarea>

</body>
</html>